use catia::{ComApartment, CatiaApp};
use catia::catia::{CatiaApi, CatiaMock};
use catia::com::is_progid_registered;
use windows::core::Result as WinResult;

fn main() -> WinResult<()> {
    let _apartment = ComApartment::init_sta()?;

    let args: Vec<String> = std::env::args().collect();
    let use_mock = args.iter().any(|a| a == "--mock");
    let progid = args
        .iter()
        .find_map(|a| a.strip_prefix("--progid="))
        .unwrap_or("CATIA.Application");

    if !use_mock {
        match is_progid_registered(progid) {
            Ok(true) => {}
            Ok(false) => {
                eprintln!(
                    "未检测到 CATIA COM 环境（ProgID: {}）。\n\
                    提示：请在已安装并注册 CATIA 的环境运行，或使用 --mock 参数。",
                    progid
                );
                return Ok(());
            }
            Err(err) => {
                eprintln!(
                    "检测 COM 环境时发生错误：{:?}。\n\
                    提示：可使用 --mock 参数运行以跳过 COM。",
                    err
                );
                return Ok(());
            }
        }
    }

    if use_mock {
        let api = CatiaMock::new();
        let ok = api.close_active_document()?;
        println!("ActiveDocument.Close() => {}", ok);
    } else {
        let app = if progid == "CATIA.Application" { CatiaApp::new()? } else { CatiaApp::with_progid(progid)? };
        let api: &dyn CatiaApi = &app;
        let ok = api.close_active_document()?;
        println!("ActiveDocument.Close() => {}", ok);
    }

    Ok(())
}